#include<iostream>
#include<pthread.h>
#include<string>
#include<unistd.h>

#define NUM 5

class Ticket
{
    private: 
        int tickets;
        pthread_mutex_t _mutex;
    
    public:
        Ticket(int num = 1000) : tickets(num)
        {
            pthread_mutex_init(&_mutex,nullptr);
        }
        ~Ticket()
        {
            pthread_mutex_destroy(&_mutex);
        }
        bool GetTicket()
        {
            //抢票逻辑
            int ret = true;
            pthread_mutex_lock(&_mutex);
            if(tickets > 0)
            {
                usleep(1000);
                std::cout << "线程：[" << pthread_self() << "] 抢到了第 " << tickets << " 张票" << std::endl;
                tickets--;
            }
            else{
                ret = false;
                std::cout << "票已抢光" << std::endl;
            }
            pthread_mutex_unlock(&_mutex);
            return ret;
        }
};

void* ThreadRun(void* args)
{
    Ticket* T = (Ticket*)args;
    while(T->GetTicket());
}

int main()
{
    pthread_t MyThread[NUM] = {0};
    Ticket* t = new Ticket(1000);
    for(int i = 0 ; i < NUM ; i++)
    {
        pthread_create(MyThread+i,nullptr,ThreadRun,(void*)t);
    }
    for(int i = 0 ; i < NUM ; i++)
    {
        pthread_join(MyThread[i],nullptr);
    }
    return 0;
}